package com.morningstone.bamboo.utils;

import freemarker.template.TemplateModelException;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 两个list同时遍历，用于两个list需要出现在同一行时
 *
 * @ClassName: DoubleListErgodic
 * @author: 7lQ
 * @date: 2021/8/6 下午 3:10
 * @Description
 * @since JDK 1.8
 */
@Component
public class DoubleListErgodic {

    public Object exec(List args) throws TemplateModelException {
        List listLeft = (List) args.get(0);
        List listRight = (List) args.get(1);
        if (CollectionUtils.isEmpty(listLeft)) {
            listLeft = new ArrayList(1);
        }
        if (CollectionUtils.isEmpty(listRight)) {
            listRight = new ArrayList(1);
        }

        if (listLeft.size() < listRight.size()) {
            //右边长
            List<Object> resultList = new ArrayList<>(listRight.size());
            for (int i = 0; i < listLeft.size(); i++) {
                Object[] arrays = {listLeft.get(i), listRight.get(i)};
                resultList.add(arrays);
            }
            //避免索引越界,单独添加右边多的元素
            for (int i = listLeft.size(); i < listRight.size(); i++) {
                Object[] arrays = {null, listRight.get(i)};
                resultList.add(arrays);
            }
            return resultList;
        } else {
            //左边长
            List<Object> resultList = new ArrayList<>(listLeft.size());
            for (int i = 0; i < listRight.size(); i++) {
                Object[] arrays = {listLeft.get(i), listRight.get(i)};
                resultList.add(arrays);
            }
            //避免索引越界,单独添加右边多的元素
            for (int i = listRight.size(); i < listLeft.size(); i++) {
                Object[] arrays = {listLeft.get(i), null};
                resultList.add(arrays);
            }
            return resultList;
        }
    }
}
